// import type { RequestConfig } from '@umijs';
import { deepGet } from '@vh-admin/pro-utils';
import { message } from 'antd';
import CryptoJs from 'crypto-js';

export let responseConfig = {
  data: 'data', // 存放数据字段
  success: 0, // 判断成功值
  code: 'code', // 错误码字段
  message: 'msg', // 返回信息字段
};

let httpError: any = {
  500: '服务器错误',
  401: '登陆失效',
  404: '数据不存在',
  403: '权限不足',
};

export const responseTableConfig = {
  data: 'data', // 表格数据列表字段名称
  total: 'total', // 表格数据列表总数字段名称
};

const showErrorMessage = (config: any, messageText: any, hookConfig: any = {}) => {
  const newConfig: any = { ...config, ...hookConfig };
  if (newConfig.errorMessageShow) {
    message.error(messageText);
  }
};

const requestConfig: any = {
  timeout: 30000,
  requestInterceptors: [
    (config: any) => {
      let httpHeadersHook = undefined;

      // @ts-ignore
      if (window?.vhAdmin?.httpHeadersHook) {
        // @ts-ignore
        httpHeadersHook = window.vhAdmin?.httpHeadersHook;
      }

      const { url, ...options } = config;
      const time = parseInt(new Date().getTime() / 1000 + '');
      const sign = CryptoJs.MD5(
        // @ts-ignore
        process.env.version + time + process.env.sign_key,
      ).toString();

      options.headers.common = {
        ...options.headers.common,
        version: process.env.version,
        time: time,
        sign: sign,
      };

      //配置默认开启错误提示
      if (options.errorMessageShow === undefined) {
        options.errorMessageShow = true;
      }

      if (typeof httpHeadersHook === 'function') {
        options.headers = httpHeadersHook(options.headers, config);
      }

      return {
        url: `${process.env.api_url}${url}`,
        ...options,
      };
    },
  ],
  responseInterceptors: [
    [
      (response: any) => {
        let hookConfig: any;

        // @ts-ignore
        if (window?.vhAdmin?.responseConfig) {
          // @ts-ignore
          responseConfig = window.vhAdmin?.responseConfig;
        }

        // @ts-ignore
        if (window?.vhAdmin?.httpError) {
          if (typeof window?.vhAdmin?.httpError === 'function') {
            httpError = window?.vhAdmin?.httpError(httpError);
          } else {
            httpError = {
              ...httpError,
              // @ts-ignore
              ...window.vhAdmin?.httpError,
            };
          }
        }
        let httpErrorHook: any = undefined;
        // @ts-ignore
        if (window?.vhAdmin?.httpErrorHook) {
          // @ts-ignore
          httpErrorHook = window?.vhAdmin?.httpErrorHook;
        }

        const { request, config } = response;

        // 如果返回的错误
        if (response.status !== 200) {
          const errMessage = httpError[response.status] || '未知错误';
          if (typeof httpErrorHook === 'function') {
            hookConfig = httpErrorHook(response.status, null, response, response.data);
          }
          showErrorMessage(config, errMessage, hookConfig);
          return Promise.reject();
        }
        // 如果是二进制数据
        if (request.responseType === 'blob') {
          if (!response.headers['content-disposition']) {
            response.data.text().then((r: any) => {
              const rdata = JSON.parse(r);
              if (typeof httpErrorHook === 'function') {
                hookConfig = httpErrorHook(
                  response.status,
                  deepGet(rdata, responseConfig.code),
                  response,
                  response.data,
                );
              }
              showErrorMessage(config, deepGet(rdata, responseConfig.message), hookConfig);
            });
            return Promise.reject();
          }

          return response;
        }
        const resData: any = response.data;

        // 如果出现 没有code的情况
        if (deepGet(resData, responseConfig.code) === undefined) {
          if (typeof httpErrorHook === 'function') {
            hookConfig = httpErrorHook(
              response.status,
              deepGet(resData, responseConfig.code),
              response,
              response.data,
            );
          }
          showErrorMessage(config, '未知错误', hookConfig);
          return Promise.reject('未知错误');
        }

        if (deepGet(resData, responseConfig.code) !== responseConfig.success) {
          if (typeof httpErrorHook === 'function') {
            hookConfig = httpErrorHook(
              response.status,
              deepGet(resData, responseConfig.code),
              response,
              resData,
            );
          }
          showErrorMessage(
            config,
            deepGet(resData, responseConfig.message) || '系统错误',
            hookConfig,
          );
          return Promise.reject(deepGet(resData, responseConfig.message) || '系统错误');
        }
        return response;
      },
      (error: any) => {
        let hookConfig: any;
        let httpErrorHook = undefined;
        // @ts-ignore
        if (window?.vhAdmin?.httpErrorHook) {
          // @ts-ignore
          httpErrorHook = window?.vhAdmin?.httpErrorHook;
        }

        const { code, config, response } = error;
        if (!response) {
          if (typeof httpErrorHook === 'function') {
            hookConfig = httpErrorHook(undefined, code, response, error);
          }
          showErrorMessage(config, error.message, hookConfig);

          return Promise.reject();
        }
        if (response.status !== 200) {
          let errMessage: any = httpError[response.status] || '未知错误';

          if (code === 'ERR_NETWORK') {
            errMessage = '网络错误!';
          }

          if (typeof httpErrorHook === 'function') {
            hookConfig = httpErrorHook(response.status, code, response, response.data);
          }

          showErrorMessage(config, errMessage, hookConfig);

          return Promise.reject();
        }
        return Promise.reject();
      },
    ],
  ],
};

export default requestConfig;
